'use strict';

const AipOcrClient = require('baidu-aip-sdk').ocr;
const fs = require('fs');

const Service = require('egg').Service;

class BaiduService extends Service {

  /**
   * 创建客户端
   */
  createClient() {
    const config = this.app.config.baiDu;
    return new AipOcrClient(config.APP_ID, config.APP_KEY, config.SECRET_KEY);
  }

  /**
   * 本地图片识别
   */
  localTextIdentify() {
    const image = fs.readFileSync(this.ctx.w_body().localPath).toString('base64');
    return this.createClient().generalBasic(image, {});
  }

  /**
   * 网络图片识别
   */
  urlTextIdentify() {
    return this.createClient().generalBasicUrl(this.ctx.w_body().url);
  }

  /**
   * 二维码识别
   */
  qrcodeIdentify() {
    const image = fs.readFileSync(this.ctx.w_body().localPath).toString('base64');
    return this.createClient().qrcode(image, {});
  }

  /**
   * 身份证识别
   */
  idcardIdentify() {
    const { localPath, isFront } = this.ctx.w_body();
    const image = fs.readFileSync(localPath).toString('base64');
    const idCardSide = isFront ? 'front' : 'back';
    return this.createClient().idcard(image, idCardSide, {});
  }

  /**
   * 银行卡识别
   */
  bankcardIdentify() {
    const { localPath } = this.ctx.w_body();
    const image = fs.readFileSync(localPath).toString('base64');
    return this.createClient().bankcard(image, {});
  }

  /**
   * 其他文字识别
   */
  otherIdentify() {
    const { localPath, keyName } = this.ctx.w_body();
    const image = fs.readFileSync(localPath).toString('base64');
    return this.createClient()[keyName](image, {});
  }
}

module.exports = BaiduService;
